﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using PIT.Labs.ProjectRepository.Owl2DotNet;
using Microsoft.SharePoint.Taxonomy;
using System.Globalization;

namespace PIT.Labs.ProjectRepository.OntologyFeature
{
    class OntologyLookupFieldControl : TextField
    {
        protected System.Web.UI.WebControls.Label prefix;
        protected System.Web.UI.WebControls.Label valueForDisplay;
        protected DropDownList itemList;

        private Dictionary<string, string> listContents = new Dictionary<string, string>();

        public IEnumerable<IIndividual> Contents { get; set; }

        public Uri RangeUri { get; set; }

        protected override string DefaultTemplateName
        {
            get
            {
                if (this.ControlMode == SPControlMode.Display)
                {
                    return this.DisplayTemplateName;
                }
                else
                {
                    return "OntologyLookupFieldControl";
                }
            }
        }

        public override string DisplayTemplateName
        {
            get
            {
                return "OntologyLookupFieldControlForDisplay";
            }
            set
            {
                base.DisplayTemplateName = value;
            }
        }

        protected override void CreateChildControls()
        {
            // TODO: Refector Method
            listContents[" "] = "-";
            if (Contents != null)
            {
                foreach(var indi in Contents){
                    listContents[indi.Uri.OriginalString] = indi.Label;
                }

                if (this.Field != null)
                {
                    var spWeb = SPContext.Current.Web;
                    foreach (SPList list in spWeb.Lists)
                    {
                        if (list.Fields.ContainsField("rdf:type"))
                        {
                            var taxoField = list.Fields["rdf:type"] as TaxonomyField;
                            if (taxoField == null) continue;

                            foreach (SPListItem item in list.Items)
                            {
                                var taxoSession = new TaxonomySession(this.Field.ParentList.ParentWeb.Site);
                                var taxoValue = item["rdf:type"] as TaxonomyFieldValue;
                                if (taxoValue != null)
                                {
                                    var term = taxoSession.GetTerm(new Guid(taxoValue.TermGuid));

                                    if (term != null && term.CustomProperties["ontology::uri"] == RangeUri.OriginalString)
                                    {
                                        listContents[item.File.UniqueId.ToString()] = item.ID + " - " + item.Name + " ["+taxoValue.Label+"]";
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (this.Field != null)
            {
                base.CreateChildControls();
                this.prefix = (System.Web.UI.WebControls.Label)TemplateContainer.FindControl("Prefix");
                this.textBox = (TextBox)TemplateContainer.FindControl("TextField");
                this.valueForDisplay = (System.Web.UI.WebControls.Label)TemplateContainer.FindControl("ValueForDisplay");
                this.itemList = (DropDownList)TemplateContainer.FindControl("ItemList");
                
                if (this.ControlMode != SPControlMode.Display)
                {
                    textBox.Width = Unit.Percentage(50);

                    foreach(var kvp in listContents){
                        itemList.Items.Add(new ListItem(kvp.Value, kvp.Key));
                    }

                    if (!this.Page.IsPostBack)
                    {
                        if (this.ControlMode == SPControlMode.New)
                        {
                            //textBox.Text = "42";
                            textBox.Text = "";
                        }
                    }
                }
                else
                {
                    valueForDisplay.Text = (String)this.ItemFieldValue;
                }

            }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                if (!this.Page.IsPostBack)
                {
                    return base.Value;
                }
                else
                {
                    string fileUrl = "";
                    if (!String.IsNullOrEmpty(itemList.SelectedValue.Trim()))
                    {
                        Guid fileGuid = new Guid(itemList.SelectedValue);
                        SPFile file = SPContext.Current.Web.GetFile(fileGuid);
                        fileUrl = SPContext.Current.Site.MakeFullUrl(file.Url);
                    }

                    base.Value = String.Format(CultureInfo.InvariantCulture, "{1};{0};{2}",itemList.SelectedValue,itemList.SelectedItem.Text, fileUrl);
                    return base.Value;
                }
            }
            set
            {
                EnsureChildControls();
                itemList.SelectedValue = ((String)value).Split(';')[1];

                //Guid fileGuid = new Guid(itemList.SelectedValue);
                //SPFile file = SPContext.Current.Web.GetFile(fileGuid);
                //string fileUrl = SPContext.Current.Site.MakeFullUrl(file.Url);

                base.Value = String.Format(CultureInfo.InvariantCulture, "{1};{0};{2}", itemList.SelectedValue, itemList.SelectedItem.Text, "");
            }
        }
    }
}
